package org.sample.net.http.pool;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {

    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static RequestConfig requestConfig = null;
    private static HttpClientBuilder httpBulder = null;

    /**
     * 连接池最大连接数
     */
    private static int maxTotalPool = 100;

    /**
     * 默认的路由最大连接数
     */
    private static int maxConPerRoute = 20;

    private static final int Timeout = 6000;

    static {
        // 创建Http连接池
        HttpRoute qq = new HttpRoute(new HttpHost("http://www.qq.com", 80));
        HttpRoute souhu = new HttpRoute(new HttpHost("http://www.souhu.com", 80));

        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotalPool);
        connectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        connectionManager.setMaxPerRoute(qq, 20);
        connectionManager.setMaxPerRoute(souhu, 20);

        // 设置请求参数
        Builder builder = RequestConfig.custom();
        builder.setSocketTimeout(Timeout);
        builder.setConnectTimeout(Timeout);
        builder.setConnectionRequestTimeout(Timeout);
        requestConfig = builder.build();

        httpBulder = HttpClientBuilder.create();
        httpBulder.setDefaultRequestConfig(requestConfig);
        httpBulder.setConnectionManager(connectionManager);
    }

    public static void main(String args[]) throws Exception {
// System.out.println(ContentType.APPLICATION_JSON.getMimeType());
// System.out.println(get("http://www.baidu.com"));
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = httpBulder.build();
        return httpClient;
    }

    public static String get(String url, String... params) throws Exception {
        HttpGet request = new HttpGet(url);
        if (params.length > 1) {
            for (int i = 0; i < params.length; i += 2) {
                String name = params[i];
                String value = params[i + 1];
                request.addHeader(name, value);
            }
        }
        HttpResponse response = null;
        try {
            response = getHttpClient().execute(request);
        } catch (Exception e) {
            request.abort();
            throw e;
        }

        String responseMessage = null;
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 300 && statusCode >= 200) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    responseMessage = EntityUtils.toString(responseEntity, Consts.UTF_8);
                    EntityUtils.consume(responseEntity);
                }
            } else {
                request.abort();
                throw new ClientProtocolException("Unexpected response status: " + statusCode);
            }
        }
        return responseMessage;
    }

    public static String post(String url, String message) throws Exception {
        StringEntity requestEntity = new StringEntity(message, Consts.UTF_8);
        requestEntity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        HttpPost request = new HttpPost(url);
        request.setEntity(requestEntity);

        HttpResponse response = null;
        try {
            response = getHttpClient().execute(request);
        } catch (Exception e) {
            request.abort();
            throw e;
        }

        String responseMessage = null;
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (300 > statusCode && statusCode >= 200) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null)
                    responseMessage = EntityUtils.toString(responseEntity, Consts.UTF_8);
            } else {
                request.abort();
                throw new ClientProtocolException("Unexpected response status: " + statusCode);
            }

        }
        return responseMessage;
    }

}